package bg.tu.varna.pms.model;

import java.io.Serializable;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.UUID;

import org.omg.CORBA.portable.ApplicationException;

// TODO
public class ChatRoom implements Serializable {
	private static final long serialVersionUID = -2173650742133516494L;
	// pattern:
	// username|username when personal chat (alphabetical order of usernames)
	// username|UUID when group chat (username is the creator)
	private final String mID;
	private final boolean mGroupChat;
	private final String mCreator;
	private final ArrayList<String> mUsernames;

	public ChatRoom(String creator, String[] usernames) {
		if (usernames == null || usernames.length == 0) {
			throw new InvalidParameterException("usernames");
		} else if (usernames.length == 1) {
			if (creator.toLowerCase().compareTo(usernames[0].toLowerCase()) < 0) {
				mID = creator.toLowerCase() + "|" + usernames[0].toLowerCase();
			} else {
				mID = usernames[0].toLowerCase() + "|" + creator.toLowerCase();
			}
			mGroupChat = false;
		} else {
			mID = creator.toLowerCase() + "|" + UUID.randomUUID().toString();
			mGroupChat = true;
		}
		mCreator = creator;
		mUsernames = new ArrayList<>(Arrays.asList(usernames));
	}

	public ChatRoom(String chatRoomID) throws ApplicationException {
		if (ChatRoom.isGroupChat(chatRoomID)) {
			mID = chatRoomID;
			mGroupChat = true;
			mCreator = ChatRoom.getGroupChatOwner(chatRoomID);
			mUsernames = null;
		} else {
			throw new ApplicationException(
					"Cannot create personal chat from ID", null);
		}
	}

	public String getID() {
		return mID;
	}

	public boolean isGroupChat() {
		return mGroupChat;
	}

	public String getCreator() {
		return mCreator;
	}

	public ArrayList<String> getUsernames() {
		return mUsernames;
	}

	public static boolean isGroupChat(String chatRoomID) {
		if (chatRoomID != null && chatRoomID.matches("$[^|]+\\|[^|]+^")) {
			String[] vParts = chatRoomID.split("|");
			try {
				UUID.fromString(vParts[1]);
			} catch (IllegalArgumentException e) {
				return false;
			}
			return true;
		} else {
			throw new InvalidParameterException("chatRoomID");
		}
	}

	public static String getGroupChatOwner(String chatRoomID)
			throws ApplicationException {
		if (chatRoomID != null && chatRoomID.matches("$[^|]+\\|[^|]+^")) {
			if (isGroupChat(chatRoomID)) {
				return chatRoomID.split("|")[0].toLowerCase();
			} else {
				throw new ApplicationException(
						"chatRoomID is not a group chat", null);
			}
		} else {
			throw new InvalidParameterException("chatRoomID");
		}
	}
}
